package com.springsecurity.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.springsecurity.dao.UserDAO;
import com.springsecurity.entities.Role;
import com.springsecurity.entities.User;

@Repository
@Transactional
public class UserDAOImpl implements UserDAO {

	@PersistenceContext
	private EntityManager entityManager;
	
	private User user = new User();

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listarTodos() {
		return entityManager.createQuery("FROM User").getResultList();
	}

	@Override
	public void salvar() {
		
		List<Role> roles = new ArrayList<Role>();
		
		roles.add(buscarPapel("ROLE_USER"));
		user.setRoles(roles);
		entityManager.persist(user);
		
		
		user = null;
	}

	@Override
	public void atualizar(User usuario) {
		entityManager.persist(usuario);
	}

	@Override
	public void remover(User usuario) {
		usuario = buscarPorID(usuario.getId());
		entityManager.remove(usuario);
	}

	@Override
	public User buscarPorID(Long id) {
		return entityManager.find(User.class, id);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public User login(String username, String password) {
		String query = "FROM User u where u.username = ? and u.password=?";
		Query q = entityManager.createQuery(query);
		q.setParameter(1, username);
		q.setParameter(2, password);

		List l = q.getResultList();

		if (l == null || l.isEmpty() || l.size() > 1) {
			return null;
		}
		return (User) l.get(0);
	}

	@Override
	public Role buscarPapel(String permissao) {
		String query = "FROM Role r where r.description = ?";
		Query q = entityManager.createQuery(query);
		q.setParameter(1, permissao);
		
		Role role = (Role) q.getSingleResult();
		
		System.out.println(role.getDescription());
		
		return role;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
	
	
}
